package com.scanner.barcodeservice;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.os.ParcelUuid;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.scanner.barcodeservice.SerialPortManager.SerialPortListener;
import com.scanner.bean.BrocastButton;
import com.scanner.bean.Event;
import com.scanner.bean.ScanSetting;
import com.scanner.database.DatabaseHelper;
import com.scanner.hardware.MyApplication;
import com.scanner.hardware.R;
import com.scanner.ui.ChooseTabSetDialog;
import com.scanner.ui.ScannerFloatView;
import com.scanner.util.BaseUtils;
import com.scanner.util.FileNode;
import com.scanner.util.HardwareInfoUtill;
import com.scanner.util.LogUtil;
import com.scanner.util.SharePreConfig;
import com.scanner.util.SoundPlayUtil;
import com.scanner.util.ThreadPoolManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class SerialPortService extends Service {
	
	private final String TAG = "SerialPortService";
	
	public static String BARCODEPORT_RECEIVEDDATA_ACTION = "com.android.serial.BARCODEPORT_RECEIVEDDATA_ACTION";
	public static String BARCODEPORT_RECEIVEDDATA_EXTRA_DATA = "DATA";
    public static final String BARCODEPROT_RECEIVEDATA_TYPE = "HARD";
	
	private SerialPortManager serialPortManager;

	private SQLiteDatabase bardb;
	private DatabaseHelper databaseHelper;
	private ScannerFloatView floatView;
	private String prefix,suffix;
	private boolean suffix_table;
	/**
	 * /sys/class/EM_BT_CONTROL/input_buf
	 * */
	private String inputPath="/sys/class/EM_BT_CONTROL/input_buf";
	
	private String inputPathEnter="/sys/class/EM_BT_CONTROL/input_buf_enter";
	

	 
	/**
	 * barcode串口写入数据
	 * */
	public static String BARCODEPORT_WRITEDATA_ACTION="com.android.portservice.BARCODEPORT_WRITEDATA_ACTION";

	public static String BARCODEPORT_HID_WRITEDATA_ACTION="com.android.scanner.HID_WRITERDATA.ACTION";

	/**
	 * barcode串口写入数据的参数DATA
	 *
	 * 注册这么多广播性能会不会很差啊。。。。。很想用eventbus来替代这些东西。
	 *
	 * */
	public static String BARCODEPORT_WRITEDATA_EXTRA_DATA = "DATA";
	public static final String BARCODEPORT_WRITER_WXTAR_BYTRDATA = "byte_date";
	public static final String BARCODEPORT_WRITER_FAUDLTE_ACTION = "com.android.barcodeservice.DEFAULT_SETTING";

	static public final String ACTION_KEYEVENT_KEYCODE_SCAN_L_DOWN = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_L_DOWN";
	static public final String ACTION_KEYEVENT_KEYCODE_SCAN_L_UP = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_L_UP";
	static public final String ACTION_KEYEVENT_KEYCODE_SCAN_R_DOWN = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_R_DOWN";
	static public final String ACTION_KEYEVENT_KEYCODE_SCAN_R_UP = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_R_UP";
	public static final String ACTION_KEYEVENT_SCAN_F_UP = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_F_UP";
	public static final String ACTION_KEYEVENT_SCAN_F_DOWN = "com.android.action.keyevent.KEYCODE_KEYCODE_SCAN_F_DOWN";
	public static final String ACTION_FLOAT_SCAN_CODE_SHOW = "com.android.barcodeservice.float_scan_code_SHOW";
	public static final String ACTION_FLOAT_SCAN_CODE_CANCEL = "com.android.barcodeservice.float_scan_code_cancel";
	public static final String ACTION_BLUETOOTH_SCANNER = "com_android_action_bluetooth_scanner";//蓝牙按键广播监听
	public static final String ACTION_BLUETOOTH_SCANNER_CANCEL = "com_android_action_bluetooth_scanner_up";

	public static final String ACTION_USERBROADCAST = "com.scanner.barcodeservice.scan_broadcast";

	 /**
     * 向input文件节点写入数据
     * */
    private WriteDataAsyncTask writeDataAsyncTask;
    /*
     * 向串口发送指令
     * */
    private WriteDataToPortAsyncTask writeDataToPortAsyncTask;
    
    private int  mCurBaudrate = -1;
    private boolean isDataValid = true;

	public static final String id = "barcode_scanner_id";
	public static final String name = "barcode_scanner";
	private String deviceNum = "";
	private String fileNodePowerOn;
	private String fileNodeCloseOpen;
	private ClipboardManager clipboardManager;
	private ScanSetting settingFormShare;

	@Override
	public void onCreate() {
		super.onCreate();
		SoundPlayUtil.init(this,SharePreConfig.getVoiceChoosePos());
		databaseHelper = new DatabaseHelper(SerialPortService.this, getFilesDir()+"/barcode.db3", null, 1);
		//适配8.0service
		NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationChannel mChannel = null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
			mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_NONE);
			notificationManager.createNotificationChannel(mChannel);
			Notification notification = new Notification.Builder(getApplicationContext(), id).build();
			startForeground(1, notification);
		}
		settingFormShare = BaseUtils.getSettingFormShare();

		//上电
		keySwitchToTiggerShangdian();
        keySwitchToTigger(TRIGGER_CANCEL_VALUE);

        //注册eventbus
		EventBus.getDefault().register(this);

  		SharedPreferences mSP = getSharedPreferences(MyApplication.SYMBOL_CONFIG_SIG, 0);
	    boolean isSig    =  mSP.getBoolean(MyApplication.SCAN_MODE_SIG,false);
	    boolean isFisrt  =  mSP.getBoolean(MyApplication.FIRST_INSTALL,true);//第一次安装
	    boolean isInited =  mSP.getBoolean(MyApplication.MODUL_INIITED,false);

	    LogUtil.v("isSig="+isSig+";isInited=="+isInited);
		try {
			openUart(SharePreConfig.getBaudRate());
		}catch (Exception e){
			LogUtil.e(e.getMessage());
		}


		serialPortManager.read();//串口读取监听
		serialPortManager.setListener(mSerialPortListener);
		
		register();//？？？？？？

        if(SharePreConfig.getXuanFuKeyScanState()){
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }else {
                    showFloatView();
                }
            }
        }


		MyApplication mApp = (MyApplication)getApplication();
	    if(isFisrt){//第一次安装
    	    SharedPreferences.Editor mEditor = mSP.edit();
    	    mEditor.putBoolean(MyApplication.FIRST_INSTALL, false);//
    	    mEditor.commit();
    	    mApp.LoadAllFactorySettings();//第一次加载所以默认数据
	    }


		deviceNum = HardwareInfoUtill.getInstance(this).getDeviceNum();

		fileNodeCloseOpen = settingFormShare.getFileNodeCloseOpen();
		fileNodePowerOn = settingFormShare.getFileNodePowerOn();
		clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

	}


	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventBusCome(Event event) {
		if (event != null) {
			if(serialPortManager != null)
			serialPortManager.onDestroySerial();
			LogUtil.i("收到eventbus信息="+event.getType());
			openUart((Integer) event.getData());
		}
	}


	
	public void openUart(int  mbaudrate){
        LogUtil.i("串口打开方法openUart=="+mbaudrate);
		    mCurBaudrate  = mbaudrate;
			serialPortManager = SerialPortManager.getInstance();
			serialPortManager.open(mbaudrate);//打开串口
//		serialPortManager.write("Rev?.");
//		serialPortManager.write("NCR");
	}

	public void openUart(int  mbaudrate,String zhiling){
		LogUtil.i("串口打开方法openUart=="+mbaudrate);
		mCurBaudrate  = mbaudrate;
		serialPortManager = SerialPortManager.getInstance();
		serialPortManager.open(mbaudrate);//打开串口
		serialPortManager.write(zhiling);
//		serialPortManager.write("NCR");
	}

	private byte[] restor = {0x04, (byte) 0xC8,0x04,0x00, (byte) 0xFF,0x30};

	public void openMotoUart(int  mbaudrate){
		mCurBaudrate  = mbaudrate;
		serialPortManager = SerialPortManager.getInstance();
		serialPortManager.open(mbaudrate);//打开串口
		serialPortManager.writeMoto(restor);
	}



	//这一大堆是什么鬼鬼鬼鬼鬼
	private byte[] InValidAnswer1 = new byte[]{ (byte)0xef,(byte) 0xbf, (byte) 0xbd };
	private byte[] InValidAnswer2 = new byte[]{ (byte)0xef,(byte) 0xbf, (byte) 0xbd, 0x00};
	private byte[] InValidAnswer3 = new byte[]{ (byte) 0x40, (byte) 0xef,(byte) 0xbf,(byte)0xbd, (byte)0x1f};

	private byte[] InValidAnswer4 = new byte[]{ (byte) 0xef,(byte) 0xbf,(byte) 0xbd};

	boolean isInvliadChars(byte[] mReceiveData, byte[] mAnswer){
		
		if(mReceiveData.length == mAnswer.length){
			for(int i = 0;  i <mAnswer.length;  i ++ ){
				if(mReceiveData[i] != mAnswer[i]){
					Log.e("isInvliadChars", "false: i = " + i);
					LogUtil.e("isInvliadChars==false: i = "+i);
					return false;
				}
			}
			LogUtil.e("isInvliadChars==true ");
			return true;
		}else{
			
			return false;
		}

	}
	
	
	private boolean isSameEnd(byte[] mReceiveData, byte[] mAnswer){
		
		for(int i = 0 ; i < mAnswer.length;  i ++){
			if(mAnswer[mAnswer.length - 1 - i] != mReceiveData[mReceiveData.length -1 - i]){
				return false;
			}
		}
		
		return true;
	}
	
	
	
	SerialPortListener mSerialPortListener = new SerialPortListener() {

				@SuppressLint("NewApi")
				@Override
				public void onResult(String data) {

					String temp = byte2hex(data.getBytes());

					LogUtil.e("串口监听到数据data="+data);
					settingFormShare = BaseUtils.getSettingFormShare();
                    LogUtil.i("onSettings是否初始化设置="+MyApplication.onSettings);
					keySwitchToTigger(TRIGGER_CANCEL_VALUE);
					if(MyApplication.onSettings){						
						return;
					}
					if(data.isEmpty() || temp.equals(" 00")){
						LogUtil.d("temp2="+temp);
						return ;
					}
					if(data.contains("�")){
						LogUtil.d("全都是看不懂");
						return;
					}
					if(temp.replace("00","").trim().equals("")){
						LogUtil.d("全都是泡沫");
					    return;
                    }

					if(isInvliadChars(data.getBytes(), InValidAnswer1)){//判断是不是InValidAnswer1类型
						LogUtil.v("isInvliadChars1");
						return ;
					}
					if(isInvliadChars(data.getBytes(), InValidAnswer2)){
						LogUtil.v("isInvliadChars2");
						return ;
					}
					
					if(isSameEnd(data.getBytes(), InValidAnswer3)){
						LogUtil.v("isInvliadChars3");
						return;
					}
					
					if(isSameEnd(data.getBytes(), InValidAnswer4)){
						LogUtil.v("isInvliadChars4");
						return;
					}
					
					if(data.startsWith("SUFCA2") && data.length() == 8){
						LogUtil.v("SUFCA2");
						return;
					}
					
					if(data.contains("ProjectRevision")){
						LogUtil.v("ProjectRevision");
						return;
					}
					LogUtil.i("isDataValid=="+isDataValid);
					if(!isDataValid ){
						return;
					}

					if(data.startsWith("DEFALT")){//初始
					    return;
                    }

					if(data.startsWith("REV")){
						LogUtil.i("removeMessages==rev");
					  return;	
					}


					prefix = SharePreConfig.getQianzhui();
					suffix = SharePreConfig.getHouzhui();


//					LogUtil.i("保存在本地的设置："+"hid="+hid+";sound="+sound+";vibrate="+vibrate+";prefix="+prefix+";suffix="+suffix+";enter="+enter+";table="+suffix_table);
					if(settingFormShare.getScanVoice()){
						SoundPlayUtil.play();
					}
					
					if(settingFormShare.getScanVibrate()){
						Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);  
						long []  pattern  = {100,400};   // 停止 开启 停止 开启   
						vibrator.vibrate(pattern,-1);
					}
					
					if( data.startsWith("DEFALT") && data.length() == 8 ){
						MyApplication mApp = (MyApplication)getApplication();
						mApp.LoadAllFactorySettings();
						if( mCurBaudrate == 9600){
							serialPortManager.write("sufca2."); //sufca2.
						}
						return;
					}
					
                    if(data.startsWith("aosmpt") || data.startsWith("AOSMPT")  || data.startsWith("hstcdt") || data.startsWith("HSTCDT")){
                    	 return;
                    }
					if(bardb == null || !bardb.isOpen()){
						bardb = databaseHelper.getWritableDatabase();
					}
					String edit_data = data.trim();//清除空格

					databaseHelper.insert(bardb,edit_data);	//插入数据数据库？
					


					if(prefix!=null){
						edit_data = prefix+edit_data;
					}

					if(suffix!=null){
						edit_data = edit_data+suffix;
					}

					if(ChooseTabSetDialog.TABTYPE2.equalsIgnoreCase(settingFormShare.getTabChoose())){//前面
						edit_data = "\t" +edit_data;
					}else if(ChooseTabSetDialog.TABTYPE3.equalsIgnoreCase(settingFormShare.getTabChoose())){//后面
						edit_data = edit_data+"\t";
					}

					if(settingFormShare.getEnterChoose()){
						edit_data = edit_data+"\n";
					}

					LogUtil.i("发送广播数据="+data);

					if(settingFormShare.isHIDChoose()){
						sendDateToHid(edit_data);
					}

					sendDateToUser(edit_data);//发送广播给用户

					//判断是否开启剪切板功能
					if(settingFormShare.isClipBoardChoose()){
						//写进系统剪切板
						ClipData clipData = ClipData.newPlainText("text", edit_data);
						clipboardManager.setPrimaryClip(clipData);
					}
				}
	};

	private void sendDateToUser(String edit_data) {
		Intent intent=new Intent(BARCODEPORT_RECEIVEDDATA_ACTION);
		intent.putExtra(BARCODEPORT_RECEIVEDDATA_EXTRA_DATA, edit_data);
		intent.putExtra(BARCODEPROT_RECEIVEDATA_TYPE,BARCODEPROT_RECEIVEDATA_TYPE);
		getApplicationContext().sendBroadcast(intent);
	}

	private void sendDateToHid(String edit_data) {
		Intent intent=new Intent();
		intent.setAction(BARCODEPORT_HID_WRITEDATA_ACTION);
		intent.putExtra(BARCODEPORT_RECEIVEDDATA_EXTRA_DATA, edit_data);
		intent.putExtra(BARCODEPROT_RECEIVEDATA_TYPE,BARCODEPROT_RECEIVEDATA_TYPE);
		getApplicationContext().sendBroadcast(intent);
	}


	/*
	* if(settingFormShare.getHIDChoose()){
						synchronized (this) {
		                writeDataAsyncTask=new WriteDataAsyncTask();
		            	writeDataAsyncTask.execute(edit_data);
						}
		            }*/

	
	@Override
	public IBinder onBind(Intent intent) {
		return new MyBinder();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		if(intent != null){
			int baud_rate = intent.getIntExtra("baud_rate", SharePreConfig.getBaudRate());
			LogUtil.d("获取到的波特率="+baud_rate);
			openUart(baud_rate,"");
		}


		if(SharePreConfig.getBlueTothScanState()){
			ThreadPoolManager.getInstance().execute(mRB);

		}
		//切换路线,为了能够不重启服务就开机，只好放这里了
		keySwitchToTiggerChange();

		return START_NOT_STICKY;
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		SoundPlayUtil.release();
		EventBus.getDefault().unregister(this);
		unregisterReceiver(receiver);
		serialPortManager.close();
		if(bardb!=null&&bardb.isOpen()){
			bardb.close();
		}
		ThreadPoolManager.getInstance().remove(mRB);
		stopForeground(true);
	}


	private void keySwitchToTiggerShangdian(){
		byte[] trigger = new byte[] { 0x31 };
		try {
			File file = new File(TextUtils.isEmpty(fileNodePowerOn) ? "/sys/devices/soc/10003000.keypad/scantrigger_enable" : fileNodePowerOn);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(trigger);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void keySwitchToTiggerChange(){
		if(settingFormShare.isSerialPortSwitch()){
			byte[] trigger =settingFormShare.getFileNodeChannelValue().getBytes();
            LogUtil.i("byte值切换接点=="+Arrays.toString(trigger)+";bytsdse值="+new String(trigger));
			try {
				File file = new File(settingFormShare.getFileNodeChannelSwitch());
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(trigger);
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
     * 向dev/uinput文件节点写入数据
     * */
    private class WriteDataAsyncTask extends AsyncTask<String, Integer, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            int res=0;
            // TODO Auto-generated method stub
            String data=params!=null&&params.length>0?params[0]:null;
			LogUtil.i("向dev/uinput文件节点写入数据;hid write data:"+ data);
            if(data!=null){
            	if(settingFormShare.getEnterChoose()){
            		FileNode.write(inputPathEnter,data);
            		LogUtil.i("文件写入数据通过enter");
            	}else{
            		FileNode.write(inputPath,data);
					LogUtil.i("文件写入数据通过!!!!!enter");
            	}
            	
            	//SoundPlayUtil.play(1);
            }
            return res;
        }
    }
    
    
    /**
	 * Broadcast receiver.
	 * */
	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action!=null){
				if(action.equals(BARCODEPORT_WRITEDATA_ACTION)){
					LogUtil.e("广播receiver :===BARCODEPORT_WRITEDATA_ACTION");
					String dataHex=intent.getStringExtra(BARCODEPORT_WRITEDATA_EXTRA_DATA);
					if(dataHex!=null){
						LogUtil.e("广播获取到数据=="+dataHex);
						writeDataToPortAsyncTask = new WriteDataToPortAsyncTask();
						writeDataToPortAsyncTask.execute(dataHex);
					}
					byte[] byteArrayExtra = intent.getByteArrayExtra(BARCODEPORT_WRITER_WXTAR_BYTRDATA);//获取到二维数组值

					if(byteArrayExtra != null && byteArrayExtra.length>0){
						writeMotoDataToRort(byteArrayExtra);
					}
					byte[] defaultSiz = intent.getByteArrayExtra(BARCODEPORT_WRITER_FAUDLTE_ACTION);
					if(defaultSiz != null && defaultSiz.length>0){
						writeDefaultSettingMoto();
					}

				}else if(action.equals(BARCODEPORT_WRITER_FAUDLTE_ACTION)){
					LogUtil.e("初始化设置");

				}else if(action.equals(ACTION_FLOAT_SCAN_CODE_SHOW)){
					LogUtil.i("显示悬浮框");
					showFloatView();
				}else if(action.equals(ACTION_FLOAT_SCAN_CODE_CANCEL)){
					LogUtil.i("关闭悬浮框");
					hideFloatView();
				}else if(action.equals(ACTION_USERBROADCAST)){//用户自定义广播
					LogUtil.i("用户自定义广播");
					keySwitchToTigger(TRIGGER_CANCEL_VALUE);
					keySwitchToTigger(TRIGGER_VALUE);
				}else if(action.equals(ACTION_BLUETOOTH_SCANNER)){
					if(SharePreConfig.getBlueTothScanState()){
						LogUtil.i("蓝牙");
						keySwitchToTigger(TRIGGER_CANCEL_VALUE);
						keySwitchToTigger(TRIGGER_VALUE);
					}
				}else if(action.equals(ACTION_BLUETOOTH_SCANNER_CANCEL)){
					if(!"Sync".equalsIgnoreCase(settingFormShare.getScanModel()))//默认是Async,防止xml设置了其他的值
						keySwitchToTigger(TRIGGER_CANCEL_VALUE);
				}else {
					ScanSetting settingFormShare = BaseUtils.getSettingFormShare();
					List<BrocastButton> brocastButtons = settingFormShare.getBrocastButtons();
					if(brocastButtons != null && brocastButtons.size()>0){
                        for (BrocastButton brocastButton : brocastButtons){
                            LogUtil.d("循环广播值=="+brocastButton.getOpenBroadcast()+";当前的值=="+brocastButton.getValue()+";action="+action);
                            if(action.equals(brocastButton.getOpenBroadcast()) && brocastButton.getValue().equalsIgnoreCase("true")){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);

                            }else if(action.equalsIgnoreCase(brocastButton.getCloseBroadcast()) && brocastButton.getValue().equalsIgnoreCase("true")){
                                if(!"Sync".equalsIgnoreCase(settingFormShare.getScanModel()))//默认是Async,防止xml设置了其他的值
                                    keySwitchToTigger(TRIGGER_CANCEL_VALUE);
                            }
                        }
                    }
				}
			}
		}
	};



	/**
	 * Write data task
	 * */
	private class WriteDataToPortAsyncTask extends AsyncTask<String, Integer, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			int res=0;

			String data=params!=null&&params.length>0?params[0]:null;
			isDataValid = true;
			res = serialPortManager.write(data);
			LogUtil.i("串口写入数据");
			return res;
		}
	}

	private void writeMotoDataToRort(final byte[] data){
		MyApplication.actionThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				serialPortManager.writeMoto(data);
			}
		});
	}

	private void writeDefaultSettingMoto(){
		MyApplication.actionThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				SerialPortManager.mInstance = null;
				serialPortManager = SerialPortManager.getInstance();
				serialPortManager.open(SharePreConfig.getBaudRate());
				serialPortManager.chushihua();
			}
		});
	}

	private Runnable mRB = new Runnable() {
		@Override
		public void run() {
			doBluetoothConnect();
		}
	};

	final int TRIGGER_VALUE = 1;
	final int TRIGGER_CANCEL_VALUE = 0;

	private void keySwitchToTigger(int value) {

		if(value == TRIGGER_VALUE && BaseUtils.isFastClick()){
			return;
		}

		byte[] trigger;

		if (value == TRIGGER_VALUE) {
//			trigger = new byte[]{0x31};        //触发

			trigger = TextUtils.isEmpty(settingFormShare.getOpenScanValue()) ? new byte[]{0x31} : settingFormShare.getOpenScanValue().getBytes();
			LogUtil.i("打开节点");
		} else {
//			trigger = new byte[]{0x30};        //取消
			trigger = TextUtils.isEmpty(settingFormShare.getCloseScanValue()) ? new byte[]{0x30} : settingFormShare.getCloseScanValue().getBytes();
			LogUtil.i("关闭节点");
		}
		try {
			File file = new File(TextUtils.isEmpty(fileNodeCloseOpen) ? "/sys/devices/soc/10003000.keypad/scan_leveltrigger_enable" : fileNodeCloseOpen);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(trigger);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LogUtil.w("节点问题==" + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			LogUtil.w("节点问题IO==" + e.getMessage());
		}
	}
	
	private void register(){
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(BARCODEPORT_WRITEDATA_ACTION);//barcode串口写入数据
			intentFilter.addAction(ACTION_KEYEVENT_KEYCODE_SCAN_L_DOWN);
			intentFilter.addAction(ACTION_KEYEVENT_KEYCODE_SCAN_L_UP);
			intentFilter.addAction(ACTION_KEYEVENT_KEYCODE_SCAN_R_DOWN);
			intentFilter.addAction(ACTION_KEYEVENT_KEYCODE_SCAN_R_UP);
			intentFilter.addAction(Intent.ACTION_SCREEN_ON);
			intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
			intentFilter.addAction(ACTION_KEYEVENT_SCAN_F_DOWN);
			intentFilter.addAction(ACTION_KEYEVENT_SCAN_F_UP);
			intentFilter.addAction(ACTION_FLOAT_SCAN_CODE_SHOW);
			intentFilter.addAction(ACTION_FLOAT_SCAN_CODE_CANCEL);
			intentFilter.addAction(ACTION_BLUETOOTH_SCANNER);
			intentFilter.addAction(ACTION_USERBROADCAST);//用户自定义广播
			intentFilter.addAction(ACTION_BLUETOOTH_SCANNER_CANCEL);
			registerReceiver(receiver, intentFilter);
	}
	
	private String byte2hex(byte [] buffer){  
        String h = "";
        for(int i = 0; i < buffer.length; i++){  
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if(temp.length() == 1){  
                temp = "0" + temp;  
            }  
            h = h + " "+ temp; 
        }  
          
        return h;  
    }
	
   public class MyBinder extends Binder{
		
		   public void openUartQR() {
				openUart(115200);
			}
			
		   public void openUartSig() {
				openUart(9600);
			}
   }
	

	private void doBluetoothConnect() {

		  BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();  
		  LogUtil.w("开启蓝牙");
          if(adapter != null){  
           
              if(!adapter.isEnabled()){   //如果蓝牙设备未开启  
                  Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  startActivity(intent);  
              }  
              
              Set<BluetoothDevice> devices = adapter.getBondedDevices();  //获得已配对的远程蓝牙设备的集合  
              if(devices.size()>0){  
                  for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){  
                	  
                      BluetoothDevice device = (BluetoothDevice)it.next();  
                      if(device.getName().equals("BLE_Handle")){
                    	    ParcelUuid  uuid[]  =  device.getUuids();

	                	    UUID mUuid = UUID.fromString(uuid[0].toString());    
	                  	    BluetoothSocket socket;
	                  	     
							try {
								socket = device.createRfcommSocketToServiceRecord(mUuid);
		                  	    socket.connect();   
		                  	    
							} catch (IOException e) {
								e.printStackTrace();
							}   
							
							break;
                      }
                  }  
              }else{
				  //不应该在子线程toast,早就应该防范的
				  Looper.prepare();
				  Toast.makeText(getApplicationContext(), R.string.str_bluetooth_prompt, Toast.LENGTH_LONG).show();
				  Looper.loop();

              }  
          }
	}


	/**
	 * 显示悬浮窗
	 */
	private void showFloatView() {
		floatView = ScannerFloatView.getInstance();
		floatView.showFloatView(getApplication(), R.layout.layout_float_click);
		floatView.setOnFloatClickListener(new ScannerFloatView.OnFloatClickListener() {
			@Override
			public void onCancelClick(View view) {
                if(!"Sync".equalsIgnoreCase(BaseUtils.getSettingFormShare().getScanModel()))
				keySwitchToTigger(TRIGGER_CANCEL_VALUE);
			}

			@Override
			public void onLongClick() {
                keySwitchToTigger(TRIGGER_CANCEL_VALUE);
				keySwitchToTigger(TRIGGER_VALUE);
			}
		});
	}

	/**
	 * 隐藏悬浮窗
	 */
	public void hideFloatView(){
		if(floatView != null){
			floatView.hideFloatView();
		}
	}


}
/*
* else if(action.equals(ACTION_KEYEVENT_KEYCODE_SCAN_L_DOWN)){
					LogUtil.e("广播receiver :KEYCODE   LEFT");
					switch (deviceNum){
						case "52":
							if (SharePreConfig.getF1KeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;

						case "86":
							if(SharePreConfig.getFKeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;
						case "62":
						default:
							if (SharePreConfig.getLeftKeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;
					}

				}else if(action.endsWith(ACTION_KEYEVENT_KEYCODE_SCAN_L_UP)){

					LogUtil.e("广播receiver :KEYCODE   LEFT UP==mode:"+scanmode);
					if (scanmode == 0)
					keySwitchToTigger(TRIGGER_CANCEL_VALUE);
				}else if(action.endsWith(ACTION_KEYEVENT_KEYCODE_SCAN_R_DOWN)){
					LogUtil.e("广播receiver :KEYCODE   RIGHT");

					switch (deviceNum){
						case "52":
							if(SharePreConfig.getF2KeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;
						case "75":
							if(SharePreConfig.getFKeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;

						case "62":
						default:
							LogUtil.i("默认正确广播==");
							if(SharePreConfig.getRightKeyScanState()){
								keySwitchToTigger(TRIGGER_CANCEL_VALUE);
								keySwitchToTigger(TRIGGER_VALUE);
							}
							break;
					}

				}else if(action.endsWith(ACTION_KEYEVENT_KEYCODE_SCAN_R_UP)){
					LogUtil.e("广播receiver :KEYCODE   RIGHT UP");
					if (scanmode == 0)
					    keySwitchToTigger(TRIGGER_CANCEL_VALUE);
				}else if(Intent.ACTION_SCREEN_ON.equals(action)){
					  isDataValid  = true;
					LogUtil.e("广播receiver :ACTION_SCREEN_ON");
				}else if(Intent.ACTION_SCREEN_OFF.equals(action)){
					 isDataValid = false;
					LogUtil.e("广播receiver :ACTION_SCREEN_OFF");
				}else if(action.equals(ACTION_KEYEVENT_SCAN_F_DOWN)){

					LogUtil.i("广播的F键摁下");
					if(SharePreConfig.getRightKeyScanState()){
						keySwitchToTigger(TRIGGER_CANCEL_VALUE);
						keySwitchToTigger(TRIGGER_VALUE);
					}

				}else if(action.equals(ACTION_KEYEVENT_SCAN_F_UP) && SharePreConfig.getRightKeyScanState()){
					LogUtil.i("广播的F键松开");
					if (scanmode == 0)
					keySwitchToTigger(TRIGGER_CANCEL_VALUE);
				}*/